<template>
  <div class="grade-import">
    <a-card title="批量导入成绩">
      <template #extra>
        <a-button @click="handleDownloadTemplate">
          <download-outlined />
          下载模板
        </a-button>
      </template>
      
      <a-steps :current="currentStep" style="margin-bottom: 30px">
        <a-step title="上传文件" />
        <a-step title="导入完成" />
      </a-steps>

      <div v-if="currentStep === 0" class="step-content">
        <a-alert
          message="操作提示"
          description="请按照Excel格式填写成绩数据：学号、姓名、年级、班级及各科成绩（课程名[课程号]格式）。系统会自动为不存在的学号创建账号，初始密码为学号。"
          type="info"
          show-icon
          style="margin-bottom: 30px"
        />
        
        <a-form layout="vertical" style="max-width: 500px; margin: 0 auto 30px">
          <a-form-item label="选择专业" required>
            <a-select 
              v-model:value="importMajor" 
              placeholder="请选择专业"
              style="width: 100%"
              show-search
              :filter-option="filterMajor"
            >
              <a-select-option 
                v-for="major in majors" 
                :key="major.id" 
                :value="major.id"
              >
                {{ major.major_name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="选择学年" required>
            <a-input-number 
              v-model:value="importTime" 
              :min="2020" 
              :max="2030" 
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
        
        <a-upload-dragger
          v-model:file-list="fileList"
          :before-upload="() => false"
          accept=".xlsx,.xls"
          :max-count="1"
          @change="handleFileChange"
          style="max-width: 600px; margin: 0 auto"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域</p>
          <p class="ant-upload-hint">
            支持Excel文件（.xlsx, .xls），单次上传不超过10MB
          </p>
        </a-upload-dragger>
        
        <!-- 文件选择成功提示 -->
        <div v-if="fileList.length > 0 && !uploading" style="max-width: 600px; margin: 20px auto 0">
          <a-alert
            message="文件准备就绪"
            :description="`已选择文件：${fileList[0].name}，大小：${(fileList[0].size / 1024).toFixed(2)} KB`"
            type="success"
            show-icon
          />
        </div>
        
        <!-- 上传进度条 -->
        <div v-if="uploading" style="max-width: 600px; margin: 30px auto 0">
          <a-progress :percent="uploadProgress" status="active" />
          <p style="text-align: center; margin-top: 10px; color: #666">
            {{ uploadStatusText }}
          </p>
        </div>
      </div>

      <div v-if="currentStep === 1" class="step-content">
        <a-result
          :status="importResult.fail_count > 0 ? 'warning' : 'success'"
          :title="importResult.fail_count > 0 ? '导入完成（部分失败）' : '成绩导入成功！'"
          :sub-title="`成功导入 ${importResult.success_count} 条成绩，失败 ${importResult.fail_count} 条`"
        >
          <template #extra>
            <a-space direction="vertical" style="width: 100%">
              <div v-if="importResult.errors.length > 0" style="max-width: 600px; margin: 0 auto">
                <a-alert
                  message="错误信息"
                  type="error"
                  show-icon
                >
                  <template #description>
                    <div style="max-height: 200px; overflow-y: auto">
                      <div v-for="(error, index) in importResult.errors" :key="index" style="margin: 4px 0">
                        {{ error }}
                      </div>
                    </div>
                  </template>
                </a-alert>
              </div>
              <a-space>
                <a-button type="primary" @click="$router.push('/grades/list')">
                  查看成绩列表
                </a-button>
                <a-button @click="currentStep = 0; fileList = []; importResult = { success_count: 0, fail_count: 0, errors: [] }">
                  继续导入
                </a-button>
              </a-space>
            </a-space>
          </template>
        </a-result>
      </div>

      <div class="step-actions" v-if="currentStep < 1">
        <a-space>
          <a-button 
            type="primary" 
            @click="handleImport"
            :loading="uploading"
            :disabled="fileList.length === 0"
          >
            开始导入
          </a-button>
          <a-button @click="$router.back()" :disabled="uploading">取消</a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { DownloadOutlined, InboxOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { gradeAPI } from '@/api/grade'
import { majorAPI } from '@/api/system'
import type { Major } from '@/api/system'
import { onMounted } from 'vue'

const currentStep = ref(0)
const fileList = ref<any[]>([])
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStatusText = ref('')
const importTime = ref<number>(new Date().getFullYear())
const importMajor = ref<number | undefined>(undefined)
const majors = ref<Major[]>([])
const importResult = ref({
  success_count: 0,
  fail_count: 0,
  errors: [] as string[]
})

// 加载专业列表
const loadMajors = async () => {
  try {
    const res = await majorAPI.getList({} as any)
    majors.value = res.data.results
  } catch (error: any) {
    message.error('加载专业列表失败: ' + (error.response?.data?.message || error.message))
  }
}

// 专业搜索过滤
const filterMajor = (input: string, option: any) => {
  const major = majors.value.find(m => m.id === option.value)
  return major?.major_name?.toLowerCase().includes(input.toLowerCase()) || false
}

const handleFileChange: UploadProps['onChange'] = (info) => {
  fileList.value = info.fileList.slice(-1) // 只保留最新的文件
}

const handleImport = async () => {
  if (fileList.value.length === 0) {
    message.error('请先选择文件')
    return
  }
  
  if (!importMajor.value) {
    message.error('请选择专业')
    return
  }
  
  uploading.value = true
  uploadProgress.value = 0
  uploadStatusText.value = '正在上传文件...'
  
  const formData = new FormData()
  formData.append('file', fileList.value[0].originFileObj)
  formData.append('time', importTime.value.toString())
  formData.append('major', importMajor.value.toString())
  
  try {
    // 模拟上传进度 (0-50%)
    const uploadInterval = setInterval(() => {
      if (uploadProgress.value < 45) {
        uploadProgress.value += 5
        uploadStatusText.value = `正在上传文件... ${uploadProgress.value}%`
      }
    }, 100)
    
    const response = await gradeAPI.batchImport(formData)
    
    // 文件上传完成
    clearInterval(uploadInterval)
    uploadProgress.value = 50
    uploadStatusText.value = '文件上传成功，正在处理数据...'
    
    // 模拟处理进度 (50-95%)
    const processingInterval = setInterval(() => {
      if (uploadProgress.value < 95) {
        uploadProgress.value += 5
      }
    }, 100)
    
    // 等待响应完成
    await new Promise(resolve => setTimeout(resolve, 500))
    
    clearInterval(processingInterval)
    uploadProgress.value = 100
    
    if (response.data.code === 200) {
      importResult.value = response.data.data
      uploadStatusText.value = `导入完成！成功 ${response.data.data.success_count} 条，失败 ${response.data.data.fail_count} 条`
      
      setTimeout(() => {
        if (response.data.data.fail_count === 0) {
          message.success('导入成功！')
        } else {
          message.warning(`导入完成，但有 ${response.data.data.fail_count} 条失败`)
        }
        currentStep.value = 1
      }, 1000)
    } else {
      uploadProgress.value = 0
      uploadStatusText.value = '导入失败'
      message.error(response.data.message || '导入失败')
    }
  } catch (error: any) {
    console.error('导入失败:', error)
    uploadProgress.value = 0
    uploadStatusText.value = '导入失败'
    message.error('导入失败: ' + (error.response?.data?.message || error.message))
  } finally {
    setTimeout(() => {
      uploading.value = false
    }, 1500)
  }
}

const handleDownloadTemplate = () => {
  message.info('模板下载功能开发中，请直接使用现有的Excel格式')
}

onMounted(() => {
  loadMajors()
})
</script>

<style scoped>
.step-content {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.step-actions {
  margin-top: 30px;
  text-align: center;
}
</style>
